package com.hjl.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author ServivE
 * @version 0.1
 * @className SqlSessionFactoryUtil
 * @description
 * @date 2024/7/29 14:50
 * @since jdk11
 */
public class SqlSessionFactoryUtil {
    //session工厂私有化
    private static SqlSessionFactory factory;

    //由于factory比较耗费资源，所以创建为单例模式
    private SqlSessionFactoryUtil() {
    }

    //静态代码块 类加载就运行
    static {
        Reader reader = null;
        try {
            //读取主配置文件
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            //获取SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //获取sqlSessionFactory
            factory = sqlSessionFactoryBuilder.build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获得session会话
     * @return
     */
    public static SqlSession getSqlSession(){
        //获取sqlSession
        return factory.openSession(true);//true代表自动提交事务
    }

}
